/* eslint-disable @typescript-eslint/no-unused-vars */
// @ts-nocheck
import { useEffect, useMemo, useRef, useState } from 'react';
import { nanoid } from 'nanoid';
import { Toast, Button, Popover, Input } from '@arco-design/mobile-react';
import { DanmakuIcon, DanmakuCloseIcon, DanmakuEmojiIcon, DanmakuOpenIcon, DanmakuSettingIcon } from '@/compnents/icons';
import { MapDanmaku, defaultDanmakuId } from '@/compnents';
// import { genDanmakus } from '@/utils';
import { usePortal } from '@/hooks';
import { useApiQueryDanmaku } from '@/hooks';
import { insertDanmaku } from '@/api';
import type { ISMap } from '@/compnents';
import './danmaku-kit.less';

type IDanmakuKit = {
  map: ISMap;
};

type IEmojiRecord = {
  id: string;
  name: string;
  native?: string;
  unified?: string;
  keywords: string[];
  shortcodes: string;
  src?: string;
};

const height = 30;
const maxEmojiCount = 5;

export const DanmakuKit = (props: IDanmakuKit) => {
  const { map } = props;
  const htmlRef = useRef(' ');
  const inputRef = useRef<HTMLDivElement>(null);
  const [danmakuEnable, setDanmakuEnable] = useState<boolean>();
  const [open, setOpen] = useState(false);
  const [danmakuReady, setDanmakuReady] = useState(false);
  const [, setDisabled] = useState(true);
  const { createPortal } = usePortal();
  const { result } = useApiQueryDanmaku({ params: {} });

  const onDanmaku = () => setOpen(!open);

  const onDanmakuChange = async () => {
    if (!map) return;
    if (typeof danmakuEnable !== 'boolean') {
      map.danmakuRenderer.setDanmakus([
        {
          id: defaultDanmakuId,
          text: '一大波弹幕即将来袭',
          time: Date.now(),
          prior: true,
          danmakuType: 'scroll',
        },
      ]);
    }
    map.danmakuRenderer.setEnable(!danmakuEnable);
    setDanmakuEnable(!danmakuEnable);
  };

  const onSendDanmaku = async () => {
    const children = inputRef.current!.childNodes;
    let text = '';
    for (let i = 0; i < children.length; i++) {
      const child = children[i];
      if (child.nodeName === 'IMG') {
        const id = (child as HTMLImageElement).getAttribute('data-id');
        if (id) text += `[${id}]`;
      } else {
        text += child.textContent;
      }
    }

    map.danmakuRenderer.send({ id: nanoid(), text, prior: true, time: Date.now(), danmakuType: 'scroll' });
    const res = await insertDanmaku({
      text,
      prior: true,
      danmakuType: 'scroll',
      lng: map.getCenter().lng,
      lat: map.getCenter().lat,
      zoom: map.getZoom(),
    });
    if (!res.data.success) Toast.error({ content: res.data.message });
  };

  const onSetDanmaku = () => {};

  const onMapDanmakuReady = () => setDanmakuReady(true);

  const onInput = () => {
    htmlRef.current = inputRef.current!.innerHTML;
    setDisabled(!inputRef.current!.innerHTML.trim());
  };

  const onEmojiSelect = (emoji: IEmojiRecord) => {
    const sel = window.getSelection();
    const element = inputRef.current;
    if (!sel || !element) return;
    const children = [...element.childNodes];
    if (children.filter((v) => v.nodeName === '#text' || v.nodeName === 'IMG').length > maxEmojiCount) {
      Toast.info({ content: `最多只能插入${maxEmojiCount}个表情`, duration: 10, stack: true });
      return;
    }
    let range = sel.getRangeAt(0);
    if (range.commonAncestorContainer !== element && !element!.contains(range.commonAncestorContainer)) {
      range = document.createRange();
      range.selectNodeContents(element!);
      range.collapse(false);
    }
    if (emoji.native) {
      range.insertNode(document.createTextNode(emoji.native));
    } else if (emoji.src) {
      const img = new Image();
      img.src = emoji.src;
      img.setAttribute('data-id', emoji.id);
      if (img.height > height) img.style.height = '100%';
      range.insertNode(img);
    }
    range.setStartAfter(range.endContainer);
    sel.removeAllRanges();
    sel.addRange(range);
    setDisabled(!inputRef.current!.innerHTML.trim());
  };

  const node = useMemo(() => {
    return (
      <div
        className="smap-danmaku-input smap-ellipsis"
        ref={inputRef}
        style={{ height, width: 200 }}
        dangerouslySetInnerHTML={{ __html: htmlRef.current }}
        contentEditable
        onInput={onInput}
        suppressContentEditableWarning
      />
    );
  }, []);

  useEffect(() => {
    if (danmakuReady && result && map) {
      map.danmakuRenderer.setDanmakus(result.data.map((v) => ({ ...v, time: new Date(v.time).valueOf() })));
    }
  }, [result, danmakuReady]);
  return (
    <>
      <DanmakuIcon className="smap-danmaku-icon" onClick={onDanmaku} />
      <MapDanmaku map={map} onReady={onMapDanmakuReady} />
      {open &&
        createPortal(
          <div className="smap-danmaku-kit">
            {!danmakuEnable ? <DanmakuCloseIcon onClick={onDanmakuChange} /> : <DanmakuOpenIcon onClick={onDanmakuChange} />}
            <DanmakuSettingIcon onClick={onSetDanmaku} />
            {/* {node} */}
            <Input />
          </div>,
        )}
    </>
  );
};
